package com.hibernate.hrm.service.login;

import com.hibernate.hrm.entity.User;
import com.hibernate.hrm.dao.UserRepository;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User findByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }

    @Transactional
    public void updateLastLogin(Integer userId, HttpServletRequest request) {
        User user = userRepository.findById(userId).orElseThrow();
        user.setLastLogin(LocalDateTime.now());
        userRepository.save(user);
    }
}
